﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using X23.Application.UserManagement;
using X23.Application.UserManagement.Dto;
using X23.Util.CacheUtil;
using X23.Util.ContextUtil;
using X23.Util.SerializationUtil;

namespace X23.Controllers
{

    [Authorize]
    public class BaseApiController : ControllerBase
    {
        public BaseApiController()
        {
            var currentUser = CurrentUser;
            ContextUtil.UserAsyncLocal.Value = currentUser == null ? null : new UserContext
            {
                Id = currentUser.Id,
                Name = currentUser.Name,
            };
        }
        private UserDto _userInfo;

        /// <summary>
        /// 当前用户
        /// </summary>
        public UserDto CurrentUser
        {
            get
            {
                if (_userInfo != null)
                {
                    return _userInfo;
                }
                if (User == null)
                {
                    return null;
                }
                var nameIdentifier = User.Claims.Where(x => x.Type == ClaimTypes.NameIdentifier).FirstOrDefault();

                if (nameIdentifier == null || !int.TryParse(nameIdentifier.Value, out int userId))
                {
                    return null;
                }
                Task<string> func() => Task.Run(async () =>
                {
                    var _userManagementService = HttpContext.RequestServices.GetRequiredService<IUserManagementService>();
                    var data = await _userManagementService.GetByIdAsync(userId);
                    return data.ToJson();
                });
                var cache = HttpContext.RequestServices.GetRequiredService<ICacheService>();
                var val = cache.GetOrCreateAsync($"CurrentUser_{userId}", func).Result;
                _userInfo = val.ToObjet<UserDto>();

                return _userInfo;
            }
        }
    }
}
